//
//  gbHeaderBiew.m
//  10-团购
//
//  Created by wangneihan on 15/12/19.
//  Copyright © 2015年 wangneihan. All rights reserved.
//

#import "gbHeaderBiew.h"

@interface gbHeaderBiew() <UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic,assign) BOOL isDsc;

@end


@implementation gbHeaderBiew

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

+(instancetype)headerBiew
{
    gbHeaderBiew *headerView = [[[NSBundle mainBundle]loadNibNamed:@"gbHeaderBiew" owner:nil options:nil]lastObject];
    return headerView;
}

-(void)awakeFromNib
{
    CGFloat iconW = self.scrollView.frame.size.width;
    CGFloat iconH = self.scrollView.frame.size.height;
    
    for (int x=0; x<5; x++) {
        NSString *imgPath = [NSString stringWithFormat:@"ad_%02d",x];
        UIImageView *imgView = [[UIImageView alloc]init];
        imgView.image = [UIImage imageNamed:imgPath];
        imgView.frame = CGRectMake(x*iconW, 0, iconW, iconH);
        [self.scrollView addSubview:imgView];
    }
    
    self.scrollView.contentSize = CGSizeMake(iconW*5, iconH);
    
    self.scrollView.delegate = self;
    
    self.scrollView.pagingEnabled =YES;
    
    self.pageControl.numberOfPages = 5;
    
    
    [self addTimer];
   // self.scrollView.showsVerticalScrollIndicator
}

-(void)addTimer
{
    NSTimer *timer =[NSTimer timerWithTimeInterval:3 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    
    self.timer = timer;
    
    //消息循环
    NSRunLoop *runloop = [NSRunLoop currentRunLoop];
    
    [runloop addTimer:timer forMode:NSRunLoopCommonModes];
    
}

-(void)nextPage
{
    int page = (int)self.pageControl.currentPage;
    if(page == 4)
    {
        self.isDsc = YES;
        //page = 0 ;
    }
    else if(page == 0)
    {
        self.isDsc = NO;
        //page ++ ;
    }
    self.isDsc ? page-- : page++;
    CGFloat x = page*self.scrollView.frame.size.width;
    [UIView animateWithDuration:1.0 animations:^{
        self.scrollView.contentOffset = CGPointMake(x, 0);
    }];
    
}

#pragma maek - scrollView的代理方法
//正在滚动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int page = (scrollView.contentOffset.x + scrollView.frame.size.width /2 ) / scrollView.frame.size.width;
    self.pageControl.currentPage = page;
}
//拖拽
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.timer invalidate];
}
//拖拽后松手
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self addTimer];
}


@end
